package com.xu.cloud.common.desensitization;

import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.Map;

/**
 * 默认数据脱敏规则工厂
 *
 * @author xuguan
 * @since 2025/3/4
 */
public class DefaultDesensitizationRuleFactory implements IDeSensitizationRuleFactory, InitializingBean {

    private final Map<SensitizationEnum, IDesensitizationRule> ruleMap = new HashMap<>();

    @Override
    public IDesensitizationRule getRule(SensitizationEnum sensitizationEnum) {
        return ruleMap.getOrDefault(sensitizationEnum, ReserveDigitsDesensitizationRule.DEFAULT_RULE);
    }

    @Override
    public void addRule(SensitizationEnum sensitizationEnum, IDesensitizationRule rule) {
        ruleMap.put(sensitizationEnum, rule);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        addRule(SensitizationEnum.DEFAULT, ReserveDigitsDesensitizationRule.DEFAULT_RULE);
        addRule(SensitizationEnum.MOBILE_NO, new RegexDesensitizationRule("^(\\d{3})\\d{4}(\\d{4})$", "$1****$2"));
        addRule(SensitizationEnum.EMAIL, new RegexDesensitizationRule("^(.{3}).*@(.*)$", "$1******@$2"));
        addRule(SensitizationEnum.ID_CARD, new ReserveDigitsDesensitizationRule(2, 4, "*", ReserveDigitsDesensitizationRule.MASK_SAME_LENGTH_DIGITS));
        addRule(SensitizationEnum.BANK_CARD, new ReserveDigitsDesensitizationRule(2, 4, "*", ReserveDigitsDesensitizationRule.MASK_SAME_LENGTH_DIGITS));
        addRule(SensitizationEnum.ADDRESS, new ReserveDigitsDesensitizationRule(8, 3, "*", 6));
        addRule(SensitizationEnum.CHINESE_NAME, new ReserveDigitsDesensitizationRule(1, 0, "*", ReserveDigitsDesensitizationRule.MASK_SAME_LENGTH_DIGITS));
        addRule(SensitizationEnum.ENGLISH_NAME, new ReserveDigitsDesensitizationRule(1, 1, "*", ReserveDigitsDesensitizationRule.MASK_SAME_LENGTH_DIGITS));
        addRule(SensitizationEnum.PASSWORD, ReserveDigitsDesensitizationRule.DEFAULT_RULE);
    }
}
